/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.yuecai.modules.yc_user_coupon.service;


import com.yuecai.modules.yc_brand.domain.YcBrand;
import com.yuecai.modules.yc_brand.repository.YcBrandRepository;
import com.yuecai.modules.yc_category.domain.YcCategory;
import com.yuecai.modules.yc_category.repository.YcCategoryRepository;
import com.yuecai.modules.yc_user_coupon.domain.YcUserCoupon;
import com.yuecai.modules.yc_user_coupon.domain.vo.YcUserCouponVo;
import com.yuecai.modules.yc_user_coupon.repository.YcUserCouponRepository;
import com.yuecai.modules.yc_user_coupon.service.dto.YcUserCouponDto;
import com.yuecai.modules.yc_user_coupon.service.dto.YcUserCouponQueryCriteria;
import com.yuecai.modules.yc_user_coupon.service.mapstruct.YcUserCouponMapper;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author dm
* @date 2020-07-21
**/
@Service
@RequiredArgsConstructor
public class YcUserCouponService {

    private final YcUserCouponRepository ycUserCouponRepository;
    private final YcCategoryRepository ycCategoryRepository;
    private final YcBrandRepository ycBrandRepository;
    private final YcUserCouponMapper ycUserCouponMapper;

    
    public Map<String,Object> queryAll(YcUserCouponQueryCriteria criteria, Pageable pageable){
        Page<YcUserCoupon> page = ycUserCouponRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<YcUserCoupon> content = page.getContent();
        ArrayList<YcUserCouponVo> ycUserCouponVos = new ArrayList<>();
        content.forEach(item->{
            Integer couponType = item.getCouponType();
            String s = couponTypeDetals(couponType, item.getConditionsId());
            YcUserCouponVo ycUserCouponVo = new YcUserCouponVo();
            BeanUtils.copyProperties(item,ycUserCouponVo);
            ycUserCouponVo.setCouponTypeDetails(s);
            ycUserCouponVos.add(ycUserCouponVo);
        });
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",page.getContent());
        map.put("totalElements",ycUserCouponVos);

        return map;
    }

    public String couponTypeDetals(Integer type,Long conditionsId){
//        1:全品类 2:限品类 3:限品牌
        if (type == 1){
            return "全品类";
        }else if (type == 2){
            Optional<YcCategory> byId = ycCategoryRepository.findById(Long.valueOf(conditionsId));
            if (byId.isPresent()){
                String name
                        = byId.get().getName();
                return name;
            }
        }else if (type == 3){
            Optional<YcBrand> byId = ycBrandRepository.findById(Long.valueOf(conditionsId));
            if (byId.isPresent()){
                String brandName
                        = byId.get().getBrandName();
                return brandName;
            }
        }
        return null;
    }

    
    public List<YcUserCouponDto> queryAll(YcUserCouponQueryCriteria criteria){
        return ycUserCouponMapper.toDto(ycUserCouponRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    
    @Transactional
    public YcUserCouponDto findById(Long id) {
        YcUserCoupon ycUserCoupon = ycUserCouponRepository.findById(id).orElseGet(YcUserCoupon::new);
        ValidationUtil.isNull(ycUserCoupon.getId(),"YcUserCoupon","id",id);
        return ycUserCouponMapper.toDto(ycUserCoupon);
    }

    
    @Transactional(rollbackFor = Exception.class)
    public YcUserCouponDto create(YcUserCoupon resources) {
        return ycUserCouponMapper.toDto(ycUserCouponRepository.save(resources));
    }

    
    @Transactional(rollbackFor = Exception.class)
    public void update(YcUserCoupon resources) {
        YcUserCoupon ycUserCoupon = ycUserCouponRepository.findById(resources.getId()).orElseGet(YcUserCoupon::new);
        ValidationUtil.isNull( ycUserCoupon.getId(),"YcUserCoupon","id",resources.getId());
        ycUserCoupon.copy(resources);
        ycUserCouponRepository.save(ycUserCoupon);
    }

    
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            ycUserCouponRepository.deleteById(id);
        }
    }

    
    public void download(List<YcUserCouponDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcUserCouponDto ycUserCoupon : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("优惠券id", ycUserCoupon.getCouponId());
            map.put("用户id", ycUserCoupon.getUserId());
            map.put("失效时间 时间戳", ycUserCoupon.getExpireDate());
            map.put("优惠券类型 关联字典表 COUPON_TYPE  1:全品类 2:限品类 3:限品牌", ycUserCoupon.getCouponType());
            map.put("条件ID coupon_type 为 2 3 时有值", ycUserCoupon.getConditionsId());
            map.put("条件的类型，0为金额，1为件数", ycUserCoupon.getConditionType());
            map.put("条件", ycUserCoupon.getConditions());
            map.put("优惠的类型，0为金额，1为折扣", ycUserCoupon.getDiscountType());
            map.put("优惠", ycUserCoupon.getDiscount());
            map.put("是否使用0否1是2锁定", ycUserCoupon.getIsUse());
            map.put("优惠券使用时间", ycUserCoupon.getUseTime());
            map.put("获取方式1注册赠券 2 物赠券赠送 3主动领取", ycUserCoupon.getCouponWay());
            map.put("发放优惠券时间", ycUserCoupon.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}